/**
 * Created by kitabi on 2017/6/16.
 */
var staffInfo={

};

var $staffDialog = $('#staffDialog');
var $sCode = $('#sCode');
var $sName = $('#sName');
var $sPwd = $('#sPwd');
var $sPhone = $('#sPhone');
var $btnStaffConfirm=$("#btnStaffConfirm");
var zNodes =[
// 			{ id:2, pId:0, name:"随意勾选 2", checked:true, open:true},
];

var menulist;//菜单列表
var setting = {
    check: {
        enable: true
    },
    data: {
        simpleData: {
            enable: true
        }
    }
};
/**
 * 获取用户数据
 */
staffInfo.queryList= function(){

    debugger;
    $("#mainTable").bootstrapTable({

        method:'POST',
        dataType:'json',
        contentType: "application/x-www-form-urlencoded",
        cache: false,
        striped: true,                              //是否显示行间隔色
        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
        url:"/staff/queryList",
        // height: $(window).height() - 110,
        // width:$(window).width(),
       // showColumns:true,
        pagination:true,
        // queryParams : queryParams,
        minimumCountColumns:2,
        pageNumber:1,                       //初始化加载第一页，默认第一页
        pageSize: 10,                       //每页的记录行数（*）
        pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
        uniqueId: "id",                     //每一行的唯一标识，一般为主键列
        showExport: true,
        exportDataType: 'all',


        paginationPreText:"<",
        paginationNextText:">",
        queryParams: function(params) {
            var userStatus= $("#userStatus").val();
            var userDateStart=$("#userDateStart").val();
            var userDateEnd=$("#userDateEnd").val();
            var userSearch= $("#userSearch").val();
            return {
                cPage: (params.offset/params.limit)+1,
                pSize: params.limit,
                status:userStatus,
                phone:userSearch,
                start:userDateStart,
                end:userDateEnd
            };
        },
        columns: [
            {
                field: 'state',
                checkbox: true,
                align: 'center',
                valign: 'middle'
            },{
                field: 'staff_id',
                title: '会员ID'
            }, {
                field: 'staff_code',
                title: '账号'
            }, {
                field: 'phone',
                title: '手机号'
            }, {
                field: 'login_date',
                title: '最后登录时间'
            }, {
                field: 'status',
                title: '状态',
                formatter: function(value,row,index){
                    if(value == 1){
                        return '正常';
                    }else{
                        return '禁用';
                    }

                }
            }, {

                field: 'status',
                title: '操作',
                align: 'center',

                formatter: function(value,row,index){
                    //value：当前field的值，即id
                    //row：当前行的数据
                    debugger;
                    var id= row.staff_id;
                    var a='<button type="button" onclick="showMenu('+id+')" style="margin-right: 5px;" class="btn btn-sm btn-primary btn-trans">权限设置</button>';
                    var status='<button type="button" onclick="updateStatus('+id+',1)" style="margin-right: 5px;" class="btn btn-sm btn-success btn-trans">启用</button>';
                    if(value==1){
                        status='<button type="button" onclick="updateStatus('+id+',0)" style="margin-right: 5px;" class="btn btn-sm btn-danger btn-trans">禁用</button>';
                    }
                    var e='<button type="button" onclick="showDetail('+index+',\'update\')" style="margin-right: 5px;" class="btn btn-sm btn-info btn-trans edit">编辑</button>';
                    var d='<button type="button" onclick="delStaff('+index+')" style="margin-right: 5px;" class="btn btn-sm btn-info btn-trans del">删除</button>';
                    return  a+status+e+d;
                }
            }]

    });

}

function updateStatus(id ,type){
    var param={
        staffId: id,
        u_status: type
    }
    Ajax.ajax({
        url: "/staff/update",
        data: param,
        type: "POST",
        dataType: 'json',
        success: function (res) {
            if (res.resultCode == 0) {
                $("#mainTable").bootstrapTable('refresh');
            } else {
                alert("操作失败");
            }
        },
        error: function(){
            alert("操作失败");
        }
    });
}


function showDetail(index,type){

    if(type == "add"){
        $sCode.prop('disabled',false);
        $btnStaffConfirm.off('click');
        $btnStaffConfirm.on('click',addStaff);
    }else if(type == "update"){
        var data= $("#mainTable").bootstrapTable("getData")[index];//获取当前列的数据


        $sCode.attr('data-id',data.staff_id);
        $sCode.val(data.staff_code);
        $sName.val(data.name);
        $sPwd.val(data.password);
        $sPhone.val(data.phone);
        $sCode.prop('disabled',true);
        $btnStaffConfirm.off('click');
        $btnStaffConfirm.on('click',updateStaff);
    }

    $staffDialog.show();

}

function delStaff(index){
    var data= $("#mainTable").bootstrapTable("getData")[index];//获取当前列的数据
    if(confirm('确定删除该管理员？')){
        debugger;
        Ajax.ajax({
            url: "/staff/delete",
            data: {staffId: data.staff_id},
            type: "POST",
            dataType: 'json',
            success:function(res){
                if (res.resultCode == 0) {
                    $("#mainTable").bootstrapTable('refresh');
                }else{
                    alert('操作失败');
                }
            },
            error: function(){
                alert('操作失败');
            }
        });
    }
    return false;
}


function showMenu(staffId) {
    var param= {

        staffId:staffId
    };

    //初始化
    for(var i =0 ;i <zNodes.length; i++){

        zNodes[i].checked=false;

    }
    $.fn.zTree.init($("#treeDemo"), setting, zNodes);

    Ajax.ajax({
        url:"/staff/queryMenuByStaffId",
        data: param,
        type: "POST",
        dataType: 'json',
        async:false,
        success:function(res){
            debugger;

            if (res.resultCode == 0) {
                var mylist = res.data;
                debugger;
                for(var i =0 ;i <zNodes.length; i++){
                    for(var n = 0;n<mylist.length;n++){
                        if(mylist[n].menu_id==zNodes[i].id){
                            zNodes[i].checked=true;
                        }
                    }
                }
                $.fn.zTree.init($("#treeDemo"), setting, zNodes);

                $("#menuList").attr("staffid",staffId).show();

            }else{
            }
        }

    });
}

var editMenuList= function(staffId){
    var param= {

        staffId:staffId
    };

    //初始化
    for(var i =0 ;i <zNodes.length; i++){

        zNodes[i].checked=false;

    }
    $.fn.zTree.init($("#treeDemo"), setting, zNodes);

    Ajax.ajax({
        url:"/staff/queryMenuByStaffId",
        data: param,
        type: "POST",
        dataType: 'json',
        async:false,
        success:function(res){
            debugger;

            if (res.resultCode == 0) {
                var mylist = res.data;
                debugger;
                for(var i =0 ;i <zNodes.length; i++){
                    for(var n = 0;n<mylist.length;n++){
                        if(mylist[n].menu_id==zNodes[i].id){
                            zNodes[i].checked=true;
                        }
                    }
                }
                $.fn.zTree.init($("#treeDemo"), setting, zNodes);

                $("#menuList").attr("staffid",staffId).show();

            }else{
            }
        }

    });
}

/**
 * 添加管理员
 */
var addStaff = function(){
    var param = {
        staffCode: $sCode.val().trim(),
        name: $sName.val().trim(),
        phone: $sPhone.val().trim(),
        password: $sPwd.val().trim()
    }
    Ajax.ajax({
        url: '/staff/add',
        data: param,
        type: "POST",
        dataType: 'json',
        success:function(res){
            if (res.resultCode == 0) {
                alert('添加成功');
                staffRest();//重置按钮

            }else{
                alert('操作失败');
            }
        },
        error: function(){
            alert('操作失败');
        }
    });
}
/**
 * 修改管理员信息
 */
var updateStaff = function(){
    var param = {
        staffId: $sCode.attr('data-id'),
        name: $sName.val().trim(),
        phone: $sPhone.val().trim(),
        password: $sPwd.val().trim()
    }
    Ajax.ajax({
        url: '/staff/update',
        data: param,
        type: "post",
        dataType: 'json',
        success:function(res){
            if (res.resultCode == 0) {
                alert('修改成功');
                staffRest();

            }else{
                alert('操作失败');
            }
        },
        error: function(){
            alert('操作失败');
        }
    });
}

function staffRest() {
    $("#mainTable").bootstrapTable('refresh');
    $staffDialog.hide();
    $sCode.val("");
    $sName.val("");
    $sPwd.val("");
    $sPhone.val("");


}

$(function(){

    debugger;
    staffInfo.queryList();

    $("#userSearchBtn").click(function(){
        $("#mainTable").bootstrapTable('refresh');
    });



    $("#menuListClose").on('click',function(){

        $("#menuList").hide();
    });


    $("#btnMenuReset").on('click',function(){

        $("#menuList").hide();
    });


    //关闭窗口
    $('#staffDialogClose').on('click',function(){

        $staffDialog.hide();
    });


    $("#btnMenuConfirm").on('click',function(){

        var newList = "";


        var treeObj=$.fn.zTree.getZTreeObj("treeDemo"),
            nodes=treeObj.getCheckedNodes(true);
        for(var i=0;i<nodes.length;i++){
            if(i==0){
                newList+=nodes[i].id;
            }else{
                newList+=","+nodes[i].id;
            }
        }

        var param = {

            "menuList":newList,
            "staffId":$("#menuList").attr("staffid")
        };
        Ajax.ajax({
            url:"/staff/updateMenuById",
            data:param,
            dataType: 'json',
            type:"POST",
            success:function(res){
                debugger;

                if (res.resultCode == 0) {
                    alert("保存成功");
//  	   				ad.queryList();
                    $("#menuList").hide();
                }else{
                    alert("保存失败");
                }
            }

        });

    });
    debugger;

    Ajax.ajax({
        url:"/staff/queryMenuList",
        type:"POST",
        async:false,
        success:function(res){
            debugger;

            if (res.resultCode == 0) {
                menuList = res.data;

                for( var x= 0;x<menuList.length;x++){
                    var node = { id:menuList[x].menu_id, pId:menuList[x].parent_menu_id, name:menuList[x].menu_name,  open:true};

                    zNodes.push(node);
                }

            }else{
            }
        }

    });
});